#!/bin/bash
get_sn() {
    SN=$(dmidecode -t system | grep 'Serial Number' | awk -F: '{print $2}' | sed 's/ //g')
    if [[ "$SN" == "ToBeFilledByO.E.M." ]]; then
        SN=$(ipmitool fru | grep Serial | awk -F: '{print $2}' | sed 's/ //g')
    fi
    if [[ -z "$SN" ]]; then
        SN="UNKNOWN_$(date +%Y%m%d)"
    fi
    echo "$SN"
}

main() {
    SN=$(get_sn)
    echo "Server Serial Number: $SN"
    BASE_DIR="/root/$SN"
    rm -rf /root/$BASE_DIR
    mkdir -p "$BASE_DIR"/{stress,hardware,health}
    mkdir -p "$BASE_DIR/hardware"/{disk,hwinfo,dimm,nic}
    mv /tmp/server_health_report* "$BASE_DIR/" 2>/dev/null
    mv /tmp/stress* "$BASE_DIR/stress/" 2>/dev/null
    mv /tmp/gpu-arp* "$BASE_DIR/stress/" 2>/dev/null
    mv /tmp/gpu-burn* "$BASE_DIR/stress/" 2>/dev/null
    mv /tmp/*.smart.log "$BASE_DIR/hardware/disk/" 2>/dev/null
    mv /tmp/fio* "$BASE_DIR/hardware/disk/" 2>/dev/null
    mv /tmp/disk.lshw.json "$BASE_DIR/hardware/disk/" 2>/dev/null
    mv /tmp/megacli* "$BASE_DIR/hardware/disk/" 2>/dev/null
    mv /tmp/storcli* "$BASE_DIR/hardware/disk/" 2>/dev/null
    mv /tmp/hpssacli* "$BASE_DIR/hardware/disk/" 2>/dev/null
    mv /tmp/setJbod.log "$BASE_DIR/hardware/disk/" 2>/dev/null
    mv /tmp/dmidecode* "$BASE_DIR/hardware/hwinfo" 2>/dev/null
    mv /tmp/bmc.mc.log "$BASE_DIR/hardware/hwinfo/" 2>/dev/null
    mv /tmp/memory.json "$BASE_DIR/hardware/dimm/" 2>/dev/null
    mv /tmp/nic_json.json "$BASE_DIR/hardware/nic/" 2>/dev/null
    mv /tmp/dmesg* "$BASE_DIR/health/" 2>/dev/null
    mv /tmp/sel* "$BASE_DIR/health/" 2>/dev/null
    mv /tmp/sdr* "$BASE_DIR/health/" 2>/dev/null
    mv /tmp/sensors.log "$BASE_DIR/health/" 2>/dev/null

    ZIP_FILE="/root/$SN.zip"
    rm -rf $ZIP_FILE
    cd /root
    zip -r "$ZIP_FILE" "$SN"


    UPLOAD_URL="http://192.168.11.18:8002/testup/$SN"
    sleep 5
    echo $UPLOAD_URL
    
    if command -v curl &> /dev/null; then
        response=$(curl -s -F "file=@$ZIP_FILE" -F "is_test=true" "$UPLOAD_URL")
    elif command -v wget &> /dev/null; then
        response=$(wget --method=POST --body-file="$ZIP_FILE" "$UPLOAD_URL" -O - 2>&1)
    else
        echo "Neither curl nor wget found. Cannot upload."
        exit 1
    fi

    echo "Upload response: $response"
    rm -rf $ZIP_FILE
}
main